﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Text;
using Trade.DAL;

namespace WebTrade
{
    public partial class Index : System.Web.UI.Page
    {
        public static string connString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        public string menu = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            Guid topFunctionId = new Guid("00000000-0000-0000-0000-000000000000");
            menu = GetTasks(topFunctionId);
        }

        //读取功能菜单定义，生成菜单JSON
        private string GetTasks(Guid functionId)
        {
            DataTable dt = SQLHelper.ExecuteDataTable(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(), CommandType.Text, "select FunctionID, ParentID, Name, URL from SysFunction", (SqlParameter[])null);

            return "[" + GetTasksString(functionId, dt) + "]";
        }

        private string GetTasksString(Guid functionId, DataTable dt)
        {
            DataRow[] rows = dt.Select("ParentID='" + functionId.ToString() + "'");

            if (rows.Length == 0) return string.Empty; ;
            StringBuilder sb = new StringBuilder();

            foreach (DataRow row in rows)
            {
                sb.Append("{");
                for (int i = 0; i < row.Table.Columns.Count; i++)
                {
                    if (i != 0) sb.Append(",");
                    sb.Append("\"");
                    sb.Append(row.Table.Columns[i].ColumnName);
                    sb.Append("\"");
                    sb.Append(":\"");
                    sb.Append(row[i].ToString());
                    sb.Append("\"");
                }
                sb.Append(",\"Children\":[");
                sb.Append(GetTasksString((Guid)row["FunctionId"], dt));
                sb.Append("]},");
            }
            return sb[sb.Length - 1] == ',' ? sb.ToString(0, sb.Length - 1) : sb.ToString();
            
        }
    }
}